import axios from "axios";
import { getToken } from "../utils/token";

const BASE_URL = "http://localhost:8080/api/";
import { message } from "antd";

const httpReqeust = axios.create({
  baseURL: BASE_URL,
  headers: { "Content-Type": "application/json" },
  timeout: 5000,
});

// 请求拦截器
// 请求拦截器
httpReqeust.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(new Error(error));
  }
);

httpReqeust.interceptors.response.use(
  (response) => {
    if (response.data.code === 401) {
      message.error("登录过期，请重新登录");
      window.location.href = "/login";
    } else if (response.data.code === 500) {
      message.error(response.data.msg);
    } else if (response.data.code === 403) {
      message.error("您没有访问权限");
    } else {
      return response.data;
    }
  },
  (error) => {
    if (error.status === 404) {
      message.error("接口不存在,请检查API地址是否正确");
    }
    return Promise.reject(new Error(error));
  }
);

export default httpReqeust;
